<template>
  <view class="vote-page">
    <!-- 顶部计时器和倒计时 -->
    <TopTimerAndCountdown
      :timer="timer"
      :countdown="countdown"
      :isVotingEnded="isVotingEnded"
      @countdownEnded="handleCountdownEnded"
	  @countdownRestart="handleCountdownRestart"
      ref="topTimerAndCountdown"
    />
    <!-- 活动banner -->
    <view class="banner">
      <image src="https://picsum.photos/id/1061/600/300" mode="aspectFill" class="banner-img"></image>
      <view class="banner-overlay">
        <view class="banner-title">2025软件开发项目评选</view>
        <view class="banner-subtitle">活动时间：2024.06.25</view>
      </view>
    </view>
    <!-- 活动信息 -->
    <view class="activity-info">
      <view class="activity-title">2025年度软件开发项目评选活动</view>
      <view class="share-btn" @click="handleShare">
        <text class="fa fa-share-alt mr-2"></text>分享
      </view>
      <view class="tabs">
        <view class="tab active">作品评比</view>
        <view class="tab">项目评选</view>
      </view>
      <view class="rule-card">
        <view class="rule-title">投票规则</view>
        <view class="rule-desc">
          请为你喜欢的摄影作品投上宝贵的一票，每位用户初始拥有票数固定，票数用尽不可继续投票<br>
          总共可投5票 每项限投1票
        </view>
      </view>
      <view class="activity-detail" @click="handleDetail">
        活动详情 <text class="fa fa-angle-right ml-2"></text>
      </view>
    </view>
    <!-- 搜索和统计 -->
    <view class="search-and-stats">
      <view class="stats">
        <view class="stat-item">
          <view class="stat-value">{{ totalVotes }}</view>
          <view class="stat-label">总票数</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ participantCount }}</view>
          <view class="stat-label">参与选手</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ voterCount }}</view>
          <view class="stat-label">投票人数</view>
        </view>
        <view class="stat-item">
          <view class="stat-value">{{ remainingVotes }}</view>
          <view class="stat-label">剩余票数</view>
        </view>
      </view>
    </view>
    <!-- 选手列表 -->
    <ParticipantList
        :participants="participants"
        :sortBy="sortBy"
        :isVotingEnded="isVotingEnded || voteStatus === '已结束'"
        :loading="loading || isVotingProcessing"
        :remainingVotes="remainingVotes"
        @handleVote="handleVote"
        @loadMore="loadMore"
      />

    <!-- 提示消息 -->
    <view 
      class="toast-message" 
      v-show="showToast"
      :class="{ 'toast-show': showToast, 'toast-success': toastType === 'success', 'toast-warning': toastType === 'warning', 'toast-info': toastType === 'info' }"
    >
      <text class="fa" 
        :class="toastType === 'success' ? 'fa-check-circle' : 
               toastType === 'warning' ? 'fa-times-circle' : 
               'fa-info-circle'"></text>
      <text>{{ toastMessage }}</text>
    </view>
    <!-- 加载中遮罩 -->
    <view class="loading-overlay" v-show="loading || isVotingProcessing">
      <view class="loading-content">
        <text class="fa fa-spinner fa-spin fa-2x mb-2"></text>
        <view class="loading-text">{{ loading ? '加载中...' : '处理中...' }}</view>
      </view>
    </view>
    <!-- 剩余票数用完弹框 -->
    <view class="ticket-used-up-modal" v-show="isTicketUsedUp">
      <view class="modal-mask" @click="closeTicketModal"></view>
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">票数禁止</text>
        </view>
        <view class="modal-body">
          <text class="modal-desc">您的剩余票数已用完，无法继续投票</text>
        </view>
        <view class="modal-footer">
          <button class="close-btn" @click="closeTicketModal">确定</button>
        </view>
      </view>
    </view>
  </view>
  
  <!-- 分享弹框 -->
  <view class="share-modal" v-show="isShareModalOpen">
    <view class="modal-mask" @click="closeShareModal"></view>
    <view class="share-modal-content">
      <view class="modal-header">
        <view class="close-btn" @click="closeShareModal">关闭</view>
      </view>
      <view class="share-content">
        <image src="/static/img/go.jpg" mode="aspectFit" class="share-qr-code"></image>
        <view class="share-tip">请截图将此二维码分享给您的朋友，一起为喜欢的作品投上宝贵一票吧!</view>
      </view>
    </view>
  </view>
</template>

<script>
import TopTimerAndCountdown from '@/component/TopTimerAndCountdown.vue';
import ParticipantList from '@/component/ParticipantList.vue';
import { get,deleteCountdown } from '@/api/countdown.js'; // 引入获取倒计时的接口
import { getAllProject, voteProject, cancelVoteProject, getRemainingVotes } from '@/api/details.js';

export default {
  components: {
    TopTimerAndCountdown,
    ParticipantList
  },
  data() {
    return {
      // 计时器和倒计时
      timer: { days: 0, hours: 0, minutes: 0, seconds: 0 },
      countdown: { days: 0, hours: 0, minutes: 10, seconds: 0 },
      
      // 统计数据
      totalVotes: 0,
      participantCount: 0,
      voterCount: 0,
      remainingVotes: 0,
      
      // 排序和加载状态
      sortBy: 'votes',
      loading: false,
      isVotingProcessing: false,
      
      // 数据列表
      participants: [],
      pageSize: 6,
      currentPage: 1,
      
      // 提示消息
      showToast: false,
      toastType: 'success',
      toastMessage: '',
      
      // 投票状态
	  // 投票状态
	  voteStatus: '',
      isVotingEnded: false,
      
      // WebSocket
      socketTask: null,
      webSocketConnected: false,
      webSocketErrorCount: 0,
	  
	  // 定时器
	  timerInterval: null,
	  countdownInterval: null,
	  
	  // 分享弹框状态
		isShareModalOpen: false,
	  
	  // 票数用完弹框状态
	  isTicketUsedUp: false
    };
  },
  created() {
  	this.startCountdownLoop(); // 启动循环
  },
  beforeCreate() {
  	clearInterval(this.countdownInterval); // 清除定时器
  },
  mounted() {
	      uni.reLaunch({
	        url: getCurrentPages()[0].route // 获取当前页面路径
	      });
  },
  onLoad(options) {
	this.voteStatus = options.voteStatus;
    this.fetchData();
    this.initWebSocket();
	this.getRemainingVotes();
  },
  methods: {
	// 启动倒计时循环
	startCountdownLoop() {
	  this.countdownInterval = setInterval(async () => {
		await this.updateCountdown();
	  }, 1000); // 每秒执行一次
	},
	// 更新倒计时的方法
	async updateCountdown() {
	  try {
		const response = await get();
		if(response){
			let newCountdown = {
			  days: response.days,
			  hours: response.hours,
			  minutes: response.minutes,
			  seconds: response.seconds
			};
			console.log(newCountdown);
			this.handUpdateCountdown(newCountdown);
			await deleteCountdown();
		}
	  } catch (error) {
		console.error('更新倒计时失败:', error);
	  }
	},
    // 处理倒计时结束事件
    handleCountdownEnded() {
      this.isVotingEnded = true;
      this.showToastMessage('info', '投票禁止');
    },
	// 处理倒计时重新开始事件
	handleCountdownRestart() {
	  this.isVotingEnded = false;
	},
    // 获取数据
	   async fetchData() {
	      this.loading = true;
	      try {
	        const response = await getAllProject();
	        const voteId = uni.getStorageSync('voteId');
	        let aaa = 0;
	        for (let i = 0; i < response.data.length; i++) {
	          if (voteId.data == response.data[i].voteId) {
	            // 添加随机风景图片
	            response.data[i].image = `https://picsum.photos/id/${Math.floor(Math.random() * 1000)}/80/80`;
	            this.participants[aaa] = response.data[i];
	            aaa++;
	          }
			}
			this.participantCount = this.participants.length;
			this.totalVotes = this.participants.reduce(
				(sum, p) => sum + (p.totalVotes || 0) + (p.totalInsideVotes || 0), 0
			);
			this.recalculateVotePercentages();
		} catch (error) {
			console.error('获取数据失败:', error);
			this.showToastMessage('error', '获取数据失败，请稍后重试');
		} finally {
			this.loading = false;
		}
	},
    // 初始化WebSocket
    initWebSocket() {
      // 从本地存储获取用户ID
      const userInfo = uni.getStorageSync('userInfo');
      const userId = userInfo?.id;
      if (!userId) {
        console.error('未获取到用户ID，无法建立WebSocket连接');
        return;
      }
      
      // 建立WebSocket连接
      this.socketTask = uni.connectSocket({
        url: `ws://localhost:8080/ws/vote?userId=${userId}`,
        success: () => {
          console.log('WebSocket连接请求已发送，用户ID:', userId);
          this.webSocketConnected = true;
          this.webSocketErrorCount = 0;
        },
        fail: (err) => {
          console.error('WebSocket连接失败:', err);
          this.showToastMessage('error', 'WebSocket连接失败，请稍后重试');
        }
      });
      
      // 监听连接打开事件
      this.socketTask.onOpen(() => {
        console.log('WebSocket连接已建立，用户ID:', userId);
        this.webSocketConnected = true;
        this.webSocketErrorCount = 0;
      });
      
      // 监听消息事件
      this.socketTask.onMessage((res) => {
        try {
          const data = JSON.parse(res.data);
          console.log('收到WebSocket消息:', data);
          
          // 处理不同类型的消息
          if (data.type === 'remainingVotes') {
            // 剩余票数更新
            this.updateRemainingVotes(data.remainingVotes);
            this.showToastMessage('success', '剩余票数已更新');
          } else if (data.type === 'projectVotes') {
            // 项目票数更新
            this.updateProjectVotes(data.projects);
          } else {
            console.log('未知类型的WebSocket消息:', data);
          }
        } catch (e) {
          console.error('解析WebSocket消息失败:', e);
        }
      });
      
      // 监听连接关闭事件
      this.socketTask.onClose((event) => {
        console.log('WebSocket连接已关闭，代码:', event.code, '原因:', event.reason);
        this.webSocketConnected = false;
        
        // 自动重连（最多5次）
        if (this.webSocketErrorCount < 5) {
          setTimeout(() => {
            this.webSocketErrorCount++;
            console.log(`尝试重新连接WebSocket (${this.webSocketErrorCount}/5)`);
            this.initWebSocket();
          }, 3000);
        } else {
          this.showToastMessage('warning', 'WebSocket连接失败，请刷新页面');
        }
      });
      
      // 监听连接错误事件
      this.socketTask.onError((err) => {
        console.error('WebSocket错误:', err);
        this.webSocketConnected = false;
        this.showToastMessage('error', 'WebSocket连接错误，请稍后重试');
      });
    },
    // 获取用户剩余票数
    async getRemainingVotes() {
      try {
        const response = await getRemainingVotes();
        if (response.code === 200) {
          this.remainingVotes = response.data;
          this.checkRemainingVotes(); // 检查是否需要显示弹框
        } else {
          console.error('获取剩余票数失败:', response.msg);
          this.showToastMessage('error', '获取剩余票数失败，请稍后重试');
        }
      } catch (error) {
        console.error('获取剩余票数失败:', error);
        this.showToastMessage('error', '获取剩余票数失败，请稍后重试');
      }
    },
   // 投票处理
   async handleVote(item) {
	   if (this.isVotingEnded || this.isVotingProcessing || this.voteStatus === '已结束') {
		   this.showToastMessage('info', this.isVotingEnded ? '投票已结束' : '操作处理中...');
		   return;
	   }
	   if (this.remainingVotes <= 0) {
		   this.isTicketUsedUp = true;
		   return;
	   }
	   this.isVotingProcessing = true;
	   try {
		   const isVoting = item.voteStatus === 'default';
		   const method = isVoting ? voteProject : cancelVoteProject;
		   const response = await method({ projectId: item.projectId });
		   if (response.code === 200) {
			   console.log(isVoting ? '投票成功' : '取消投票成功');
			   this.showToastMessage('success', isVoting ? '投票成功' : '取消投票成功');
		   } else {
			   this.showToastMessage('error', response.msg || '操作失败');
		   }
	   } catch (error) {
		   console.error('投票请求失败:', error);
		   this.showToastMessage('error', '网络错误，请稍后重试');
	   } finally {
		   this.isVotingProcessing = false;
	   }
   },
    // 更新项目票数
    updateProjectVotes(projects) {
      if (!projects || !projects.length) return;
      
      // 更新本地项目列表中的票数
      projects.forEach(updatedProject => {
        const index = this.participants.findIndex(p => p.projectId === updatedProject.projectId);
        if (index !== -1) {
          this.participants[index] = {
            ...this.participants[index],
            totalVotes: updatedProject.totalVotes,
            totalInsideVotes: updatedProject.totalInsideVotes
          };
        }
      });
      
      // 重新计算总票数和百分比
      this.totalVotes = this.participants.reduce(
        (sum, p) => sum + (p.totalVotes || 0) + (p.totalInsideVotes || 0), 0
      );
	   
      this.recalculateVotePercentages();
      
      // 显示更新提示
      this.showToastMessage('success', '投票数据已更新');
    },
    // 更新剩余票数
    updateRemainingVotes(remainingVotes) {
      this.remainingVotes = remainingVotes;
      this.checkRemainingVotes();
    },
    // 检查剩余票数并显示弹框
    checkRemainingVotes() {
      if (this.remainingVotes <= 0 && !this.isTicketUsedUp) {
        this.isTicketUsedUp = true;
      }
    },
    // 关闭票数用完弹框
    closeTicketModal() {
      this.isTicketUsedUp = false;
    },
    // 重新计算投票百分比
    recalculateVotePercentages() {
      if (this.totalVotes <= 0) {
        this.participants.forEach(p => p.votePercent = '0.0');
        return;
      }
      
      this.participants.forEach(p => {
        const total = (p.totalVotes || 0) + (p.totalInsideVotes || 0);
        p.votePercent = (total / this.totalVotes * 100).toFixed(1);
      });
    },
    // 显示提示消息
    showToastMessage(type, message) {
      this.toastType = type;
      this.toastMessage = message;
      this.showToast = true;
      
      setTimeout(() => {
        this.showToast = false;
      }, 2000);
    },
    // 加载更多数据
    loadMore() {
      if (this.loading || this.isVotingProcessing || this.isVotingEnded) return;
      
      this.loading = true;
      
      // 模拟加载更多数据
      setTimeout(() => {
        this.currentPage++;
        this.loading = false;
      }, 1000);
    },
    // 分享功能
      handleShare() {
        this.isShareModalOpen = true;
      },
      
      // 关闭分享弹框
      closeShareModal() {
        this.isShareModalOpen = false;
      },
    // 查看活动详情
    handleDetail() {
      uni.showToast({
        title: '活动详情开发中',
        icon: 'none'
      });
    },
    // 导航切换
    navigateTo(page) {
      uni.showToast({
        title: `${page}页面将在实际项目中实现`,
        icon: 'none'
      });
    },
    handUpdateCountdown(newCountdown){
      console.log(newCountdown,111);
      this.$refs.topTimerAndCountdown.handleStartManualCountdown(newCountdown);
    }
  },
  onUnload() {
    if (this.socket) {
      this.socket.close();
    // 清理资源
    if (this.timerInterval) clearInterval(this.timerInterval);
    if (this.countdownInterval) clearInterval(this.countdownInterval);
    if (this.socketTask) {
      this.socketTask.close();
      this.socketTask = null;
    }
  }
  }
};
</script>

<style scoped>
/* 页面整体样式 */
.vote-page {
  min-height: 100vh;
  background-color: #f8f8f8;
}

/* 顶部计时器和倒计时样式 */
.top-timer {
  background-color: #333;
  color: white;
  padding: 10px;
  text-align: center;
}

/* 活动banner样式 */
.banner {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.banner-img {
  width: 100%;
  height: 100%;
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
  padding: 20px;
  color: white;
}

.banner-title {
  font-size: 20px;
  font-weight: bold;
}

.banner-subtitle {
  font-size: 14px;
  margin-top: 5px;
}

/* 活动信息样式 */
.activity-info {
  padding: 15px;
  background-color: white;
  margin-bottom: 10px;
}

.activity-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.share-btn {
  float: right;
  color: #666;
  font-size: 14px;
}

.tabs {
  display: flex;
  margin: 15px 0;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 10px;
  border-bottom: 2px solid #eee;
  font-size: 16px;
}

.tab.active {
  border-bottom-color: #f56c6c;
  color: #f56c6c;
  font-weight: bold;
}

.rule-card {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
}

.rule-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.rule-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.activity-detail {
  text-align: center;
  color: #007aff;
  font-size: 14px;
  padding: 10px 0;
}

/* 搜索和统计样式 */
.search-and-stats {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.search-box {
  display: flex;
  margin-bottom: 15px;
}

.search-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 5px 0 0 5px;
}

.search-btn {
  background-color: #f56c6c;
  color: white;
  padding: 10px 15px;
  border-radius: 0 5px 5px 0;
}

.stats {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

/* 选手列表样式 */
.participant-list {
  background-color: white;
  padding: 15px;
}

/* 底部导航样式 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: white;
  border-top: 1px solid #eee;
  padding: 10px 0;
}

.nav-item {
  flex: 1;
  text-align: center;
}

.nav-item.active {
  color: #f56c6c;
}

/* 提示消息样式 */
.toast-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px 15px;
  border-radius: 5px;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  z-index: 1000;
}

.toast-show {
  opacity: 1;
}

.toast-success {
  background-color: rgba(60, 179, 113, 0.9);
}

.toast-warning {
  background-color: rgba(255, 140, 0, 0.9);
}

.toast-info {
  background-color: rgba(70, 130, 180, 0.9);
}

/* 投票结束遮罩样式 */
.vote-ended-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.overlay-content {
  text-align: center;
  color: white;
}

.overlay-title {
  font-size: 20px;
  font-weight: bold;
  margin: 10px 0;
}

.overlay-desc {
  font-size: 16px;
}

/* 加载中遮罩样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 998;
}

.loading-content {
  background-color: white;
  padding: 20px 30px;
  border-radius: 10px;
  text-align: center;
}

.loading-text {
  margin-top: 10px;
  font-size: 16px;
}

/* 票数用完弹框样式 */
.ticket-used-up-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  background-color: #fff;
  border-radius: 12px;
  width: 80%;
  max-width: 400px;
  padding: 30px 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  text-align: center;
  margin-bottom: 20px;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.modal-body {
  text-align: center;
  margin-bottom: 20px;
}

.modal-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.modal-footer {
  display: flex;
  justify-content: center;
}

.close-btn {
  background-color: #f56c6c;
  color: #fff;
  padding: 10px 30px;
  border-radius: 20px;
  font-size: 14px;
}

/* 公共样式 */
.mr-2 {
  margin-right: 5px;
}

.ml-2 {
  margin-left: 5px;
}

.mb-2 {
  margin-bottom: 5px;
}

.mb-3 {
  margin-bottom: 10px;
}

.fa {
  font-family: 'FontAwesome';
}

/* 分享弹框样式 */
.share-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.share-modal-content {
  position: relative;
  background-color: #fff;
  border-radius: 12px;
  width: 90%;
  max-width: 450px;
  padding: 30px 20px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.share-modal .modal-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.share-modal .close-btn {
  font-size: 16px;
  color: #666;
  padding: 5px 10px;
}

.share-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.share-qr-code {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.share-tip {
  font-size: 28rpx;
  color: #333;
  text-align: center;
  line-height: 1.5;
}
</style>